import {createRouter, createWebHistory} from 'vue-router'
import {TOKEN} from '@/common/constants'

const LoginPage = () => import('../components/LoginPage.vue')

const routes = [
    {
        path: "/",
        redirect: '/home'
    },
    {
        path: '/login',  // 登陆页面
        name: "loginPage",
        component: LoginPage
    },
    {
        path: '/home',  // 首页
        name: "homePage",
        component: () => import('@/components/HomePage.vue'),
        children: [
            {
                // 添加文章页面
                path: 'addArticle',
                component: () => import('@/components/AddArticlePage.vue')
            },
            {
              // 文章列表页面k
              path: 'articleList',
              component: () => import('@/components/ArticleListPage.vue')
            },
        ]
    },
    {
        path: '/article/:articleId',  // 文章内容页
        name: "article",
        component: () => import('@/components/article/ArticleView.vue'),
        props: true
    },
]
const routerHistory = createWebHistory()
const router = createRouter({
    history: routerHistory,
    routes
})

router.beforeEach((to, from, next) => {
    // 获取到 token值
    const token = localStorage.getItem(TOKEN);
    // 如果 token 的值为空且访问的路径不是登陆页面，则转发到登陆页面
    // 如果 token 不为空则放行
    if (!token && to.path !== '/login') {
        next('/login')
    } else {
        next()
    }
})

export default router